<!-- 权限配置页面 -->
<template>
  <div class="page">
    <div class="page_filter">

      <!-- 启用状态 -->
      <el-select v-model="form.flag" clearable placeholder="请选择启用状态">
        <el-option
          v-for="item in flagList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>

      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
    <el-button
      icon="el-icon-plus"
      @click.stop="handleAdd"
      class="common_btn-small">
      新增配置
    </el-button>
    <!-- Table表单部分 -->
      <el-table :data="tableList" border>
        <el-table-column prop="companyName" label="名称" width="150"   show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="授权id" width="120" prop="accessId"/>
        <el-table-column prop="encryptionKey" show-overflow-tooltip label="授权秘钥" width="220"/>
        <el-table-column prop="deptTreeName" label="关联的管养单位" width="250"   show-overflow-tooltip/>
        <el-table-column prop="flag" label="启用状态" width="180">
          <span v-show="tableList.flag=1">已启用</span>
          <span v-show="tableList.flag!=1">未启用</span>
        </el-table-column>
        <el-table-column prop="explanation" label="描述" width="215"   show-overflow-tooltip/>
        <el-table-column prop="createTime" label="时间" width="100"   show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.createTime | formatTimer}}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"   show-overflow-tooltip/>
        <el-table-column prop="ipWhiteList" label="ip白名单" width="180"/>
         <el-table-column prop="ipWhiteList" label="操作" width="80"  style="color: red">
          <template slot-scope="scope">
            <button class="btn_edit" @click="handleEdit(scope.row)" stype="color:white !important">编辑</button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
           :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
        :total="total"/>
    </div>
    <!-- 具体form表单 -->
    <div class="openFrom">
      <!-- 新增 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="dialogTitle"
        :visible.sync="isShowDialog"
        :before-close="clearValidate"
        width="600px"
      >
        <el-form
          label-position="right"
          ref="form"
          :rules="rules"
          :model="currentRow"
          label-width="90px"
          class="form_width-200"
        >
          <el-form-item label="名称" prop="companyName">
            <el-input v-model="currentRow.companyName" placeholder="请输入名称">
            </el-input>
          </el-form-item>
          <el-form-item label="授权ID" prop="accessId">
            <el-input
              v-model="currentRow.accessId"
              placeholder="请输入授权id"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="授权秘钥"
            prop="encryptionKey"
            class="from-secend"
          >
            <el-input
              v-model="currentRow.encryptionKey"
              placeholder="请输入授权秘钥"
              :disabled="isDisabled"
              style="width: 70% ;margin-right: 1%"
            >
            </el-input>
            <el-button @click="createCode" class="common_btn-defalut">生成秘钥</el-button>
          </el-form-item>
          <el-form-item label="描述" prop="explanation">
            <el-input v-model="currentRow.explanation" placeholder="请进行描述">
            </el-input>
          </el-form-item>
          <el-form-item
            label="关联的管养单位"
            label-width="270"
            prop="deptTreeId"
          >
            <organization-unit
              v-model="currentRow.deptTreeId"
              :change-on-select="true"
              style="width: 81%"
              placeholder="选择管养单位"
              @change="changeDept"
            ></organization-unit>
          </el-form-item>
          <el-form-item label="路线选择" label-width="250" prop="roadId">
            <el-select
              style="width: 81%"
              multiple
              v-model="currentRow.roadId"
              filterable
              clearable
              placeholder="选择路线"
            >
              <el-option
                v-for="item in deptRoadList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用状态" prop="flag">
            <!-- <el-radio-group v-model="currentRow.flag">
           <el-radio v-for="item in flagList" :key="item.code" :label="item.code">{{item.name}}</el-radio>

            </el-radio-group> -->
              <el-radio-group v-model="currentRow.flag">
            <el-radio-button v-for="item in  flagList" :key="item.code" :label="item.code">{{item.name}}
                  </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="IP白名单" prop="ipWhiteList">
            <el-input
              v-model="currentRow.ipWhiteList"
              placeholder="请输入ip白名单"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button
            class="common_btn-white"
            @click="clearValidate"
            style="background: white !important; color: black !important"
            >取消</el-button
          >
          <el-button
            class="common_btn-defalut"
            type="primary"
            @click="validateForm"
            >确定</el-button
          >
        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import Enums from '@/utils/enums'
import { filterEmpty } from "@/services/request";
import Format from "@/utils/format";
import OrganizationUnit from "@/components/organization-unit/all";
import { getRoadSelectList } from "@/services/model/road-mgmt";
import {
  postKeyInformation,
  getKeyList,
  modifyKeyInformation,
} from "@/services/model/openapi";
import md5 from "js-md5";
export default {
  mixins:[Enums],
  data() {
    return {
      // 启用列表
      EnumSysBoolean:[],
      flagList:[],
      form1: {},
      // 列表数据
      tableList: [],
      form: {
        page: 1,
        pageSize: 10,
      },
      total:0,
      rules: {
       accessId: [
          { required: true, message: "请输入id" },
          // {
          //   min: 4,
          //   max: 10,
          //   message: "长度在 4 到 10 个字符",
          //   trigger: "blur",
          // },
          // {
          //   required: true,
          //   message: "请输入纯大写字母",
          //   pattern: /^[A-Z\d]+$/,
          //   trigger: "blur",
          // },
        ],
      },
      selectModel: 0, // 下拉选择model
      searchModel: "", // 搜索框model
      // tableList: [],
      isShowDialog: false, // 是否显示弹窗

      currentRow: [{ radio1: "未启用" }], // 新增数据
      cityModel: "",
      checked: true,
      deptRoadList: [],
      // input 输入框是否可以使用
      isDisabled: true,
      // input输入框
    };
  },
  components: { OrganizationUnit },
  computed: {
    // 弹窗的title
    dialogTitle() {
      return this.currentRow.id ? "编辑配置" : "新增配置";
    //  if(this.currentRow.id ? '111')


    },
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      return Format(new Date(timer), "yyyy-MM-dd");
    },
    // 0正常，1锁定
    getStatusBtnMap(type) {
      return type ? "停用" : "启用";
    },
  },
  methods: {
    //  获取页码
    handleSizeChange(val) {
      this.form.pageSize = val;
      this.queryList();
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val;
      this.queryList();
    },
    //获取列表数据
    async queryList() {
      let res = await getKeyList(this.form);
      // console.log(res.data);
      if (res.code === 200) {
        this.tableList = res.data?.records || [];
        this.form.size = Number(res.data?.size);
        this.form.total = Number(res.data?.total);
        //  console.log(this.tableList)
      }
    },
    //获取组织下的路线列表
    async getRoadListByDept(deptId) {
      const { data } = await getRoadSelectList({ deptId: deptId });
      return data;
    },
    // 获取路线
    async changeDept() {
      // console.log(this.currentRow.deptTreeId);
      this.deptRoadList = await this.getRoadListByDept(
        this.currentRow.deptTreeId
      );

      this.depList();
      // console.log(this.deptRoadList);
      // console.log(this.currentRow.roadId);
    },
    depList() {
      this.deptRoadList.map(function (items, index, array) {
        return index;
      });
    },
    getUUID() {
      var s = []
      var hexDigits = '0123456789ABCDEFGHIGKLMNOPQRSTUVWXWZ'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = ''
      var uuid = s.join('')
      return uuid
    },
    // 随机生成秘钥
    createCode() {
      // var code = '';
      // //设置长度，这里看需求，我这里设置了4
      // var codeLength = 10;

      // //设置随机字符
      // var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

      // //循环codeLength 我设置的4就是循环4次
      // for (var i = 0; i < codeLength; i++) {
      //     //设置随机数范围,这设置为0 ~ 36
      //     var index = Math.floor(Math.random() * 9);

      //     //字符串拼接 将每次随机的字符 进行拼接
      //     code += random[index];
      // }

      // // 将拼接好的字符串赋值给展示的code
      // let encryptionKey = md5(this.currentRow.accessId);
      // this.isDisabled=flase
      // this.currentRow.encryptionKey = encryptionKey;

      // console.log(this.currentRow.accessId);
      this.isDisabled = false;
      var encryptionKey = md5(this.currentRow.accessId);
      this.miYaoBianHua();
    },
    miYaoBianHua() {
      let encryptionKey = this.getUUID();
      this.currentRow.encryptionKey = encryptionKey;
    },


    // 关闭弹窗之前清楚表单校验提示
    clearValidate() {
      this.$refs.form.clearValidate();
      this.isShowDialog = false;
    },
    // 表单提交
    async validateForm() {
 this.$refs.form.validate((valid) => {
        if (valid) {
          this.currentRow = filterEmpty(this.currentRow)

          this.submitData()
        }
      })
    },
    // 新增编辑提交数据
    async submitData () {
      // 根据ID判断使用新增还是编辑
      let action = this.currentRow.id ? modifyKeyInformation:postKeyInformation
      this.currentRow = {...this.currentRow,handleItemList:this.formationList}
      // return
      let res = await action(this.currentRow)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.currentRow.id ?'编辑成功':'添加成功'
        })
        this.isShowDialog = false
        this.queryList()
      }
    },
    // 新增数据
    handleAdd() {
      this.currentRow = {};
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
            // this.isShowDialog = false
      });
    },
    /**
     * row  当前操作行的对象
     */
    handleEdit(row) {
      this.currentRow = { ...row};
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
  },
  mounted() {
    this.queryList();
     this.queryDictList(['EnumSysBoolean'], ['flagList'])
  },
  activated() {
    this.queryList();
    // 获取当前用户的角色列表
  },
};
</script>
<style lang='less' scoped>
/* //@import url(); 引入公共css类 */

.openApi {
  // background: red;
  width: 80%;
  height: 100%;
  margin: 0 auto;
  .el-button {
    background: #1990FE !important;
    color: white !important;
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .openFrom {
    .from-secend {
      // background: red;
      position: relative;
      .el-button {
        position: absolute;
        right: 0;
        bottom: -20px;
        border-radius: 0 !important;
        // height: 98%;
      }
    }
    // /deep/.el-form-item__label {
    //   width: 30% !important;
    //   background: brown;
    // }
    // /deep/.el-input__inner {
    //   width: 70% !important;
    // }
    // /deep/.el-form {
    //   background: yellowgreen;
    // }
    // /deep/.el-form-item {
    //   background: blue;
    //   display: flex;
    // }
  }
}

// table
// 修改头部样式：

.btn_edit{
  color: #00aa09 !important;
}
</style>
